<?php

namespace App\Http\Middleware;

use App\Models\Permission;
use App\Models\Users;
use Closure;
use Facade\FlareClient\Api;
use Illuminate\Auth\Events\Failed;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Route;
use Tymon\JWTAuth\Facades\JWTAuth;
use App\Models\ApiLogs;

class AccessLog
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse)  $next
     * @return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse
     */
    public function handle(Request $request, Closure $next)
    {

        $traceId = md5(time() . mt_rand(1, 1000000));

        // 记录请求信息
        $requestMessage = [
            'traceId' => $traceId,
            'url' => $request->url(),
            'path'=>substr($request->getPathInfo(), 1),
            'method' => $request->method(),
            'ip' => $request->getClientIp(),
            'headers' => $request->header('Authorization'),
            'params' => $request->all()
        ];
//        dd(substr($request->getPathInfo(),1));
        if(substr($request->getPathInfo(), 1)=="auth/login"){
            $user = Users::where('name', $request->get("username"))
                ->where('password', md5($request->get('password')))
                ->first();
            if(!$user){
                return Failed(40004,["File"=>"AccessLog","Line"=>__LINE__]);
            }
            if($user->status!=1){
                return Failed(40005,["File"=>"AccessLog","Line"=>__LINE__]);
            }
        }elseif(strstr(substr($request->getPathInfo(), 1), "miniapp")){
            $user = new class{};
            $user -> id = 999999;//微信用户 默认ID
            $user->name = '微信用户';

        }else{
            $user= JWTAuth::parseToken()->authenticate();
        }
        Log::info("请求信息：", $requestMessage);
        $urlArr = array_values (array_filter(explode("/",$request->getPathInfo())));

        if(preg_match("/^\d*$/",$urlArr[count($urlArr)-1])){
            array_pop($urlArr);
            $urlArr[] = '';
            $api_url = implode("/",$urlArr);
            $permission = Permission::where([['api_route','like','%'.$api_url."%"],['method',$request->method()]])->first();
        }else{
            $permission = Permission::where([['api_route',substr($request->getPathInfo(), 1)],['method',$request->method()]])->first();
        }

        $respone = $next($request);
        $data = [
            'user_id'=>$user->id,
            'user_name'=>$user->nickname,
            'api'=>substr($request->getPathInfo(), 1),
            'api_name'=>$permission->name,
            'method' =>$request->method(),
            'request_body' =>json_encode($request->all(),JSON_UNESCAPED_UNICODE),
            'request_header' =>json_encode($request->header('Authorization'),JSON_UNESCAPED_UNICODE),
            'request_ip' =>$request->getClientIp(),
        ];
        $responeData = [
            'traceId' => $traceId,
            'respone' => json_decode($respone->getContent(), true) ?? ""
        ];
        $data['response_body'] =json_encode(json_decode($respone->getContent(), true) ?? "",JSON_UNESCAPED_UNICODE);
        $data['created_at'] = date("Y-m-d H:i:s");
        $data['updated_at'] = date("Y-m-d H:i:s");
        if(!ApiLogs::create($data)){
            Log::error("记录ApiLog失败：", $responeData);
        }
        Log::info("返回信息：", $responeData);
        return $respone;
    }
}
